package com.wy.business.developer.apps.services;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.wy.business.market.home.pojos.TMarketScreenshots;
import com.wy.business.market.market.pojos.TSysInterfaceApp;
import com.wy.business.market.market.pojos.TSysInterfaceInfo;
import com.wy.framework.constants.Constants;
import com.wy.framework.constants.DBConstant;
import com.wy.framework.constants.RtnCodeConstant;
import com.wy.framework.dao.ErrorSqlException;
import com.wy.framework.pojos.TSysFunction;
import com.wy.framework.pojos.TSysFunctionUpdatePending;
import com.wy.framework.pojos.TSysFunctionVersion;
import com.wy.framework.pojos.TSysLocalNetwork;
import com.wy.framework.pojos.TSysUserinfo;
import com.wy.framework.pojos.TSysUserselectedfunction;
import com.wy.framework.services.AbstractBaseService;
import com.wy.component.dataConvert.Base64Image;
import com.wy.component.dataConvert.BeanUtil;
import com.wy.component.dataConvert.StringUtil;

/**
 * 项目名称：openportal
 * 类名称：AppManageService
 * 类描述：我的APP仓库_APP管理
 * 创建人：张旭星
 * 创建时间：2016-3-21 上午11:47:28
 * 修改人：张旭星
 * 修改时间：2016-3-21 上午11:47:28
 * 版本信息：@version 1.0
 * Copyright (c) 2016万雍科技（上海）有限公司-版权所有  
 * 修改备注：
 * @version 
 */
@Service
public class AppSubmitService extends AbstractBaseService {

	private static final char[] object = null;
	private static Logger logger = LoggerFactory
			.getLogger(AppSubmitService.class);

	public String saveApp(String[] imgShots, String appIcon, String functionName, 
			String functionNameEn, String deploymentType, String actionUrl, String appZipUrl, 
			String appSize, String versionName, String[] ipAddress, String[] ipAddressDesc, 
			String net_setting,  String manageUrl, String description, 
			String upgradeContent, String[] authRows, String functionId) throws IOException, ErrorSqlException {
		//redis里取登录人
		TSysUserinfo tSysUserinfo = loginUser();
		
		TSysFunction f = new TSysFunction();
		f.setActionUrl(actionUrl);
		f.setAppDownCtn(0);
		f.setAppZipUrl(appZipUrl);
		
		//byte计算为M
		File appZipFile=new File(this.getClass().getResource("/").getPath().replace("WEB-INF/classes/", "")+appZipUrl);
		f.setAppSize(StringUtil.convertFileSize(appZipFile.length()));
		
		f.setState(Constants.NEW_APP_PENDING);
		f.setDeploymentType(deploymentType);
		f.setDescription(description);
		f.setFunctionId(functionId);
		f.setFunctionName(functionName);
		f.setFunctionNameEn(functionNameEn);
		f.setInternetConfig("");
		
		//应用图标
		String appIconPathHead = this.getClass().getClassLoader().getResource("/").getPath().replace("/WEB-INF/classes", "");
		String appIconPathBody = "/upload/appIconImg/"+UUID.randomUUID().toString()+".jpg";
		Base64Image.GenerateImage(appIcon, appIconPathHead + appIconPathBody);
		f.setIconName(appIconPathBody);
		f.setIsAvailable("1");
		f.setIsMenuVisiable("0");
		f.setIsSystemFunction("0");
		f.setManageUrl(manageUrl);
		f.setOperatorAccount(tSysUserinfo.getUserId());
		f.setOperatorName(tSysUserinfo.getUserName());
		f.setPriority(1);
		f.setProvider(tSysUserinfo.getUserName());
		f.setSubmitTime(new Timestamp(new Date().getTime()));
		f.setUpdateTime(new Timestamp(new Date().getTime()));
		f.setUpDownState("0");
		f.setUpgradeContent(upgradeContent);
		f.setVersionName(versionName);
		f.setVersionNo(1);
		f.setViewdTimes(0);
		dataBaseDao.save(f);
		
		//局域网信息,如果类型为局域网，才入库
		if(ipAddress!=null && StringUtils.equals(f.getInternetConfig(), "1")){
			for(int i=0;i<ipAddress.length;i++){
				TSysLocalNetwork tSysLocalNetwork = new TSysLocalNetwork();
				tSysLocalNetwork.setAddress(ipAddressDesc[i]);
				tSysLocalNetwork.setIp(ipAddress[i]);
				tSysLocalNetwork.setIsavailable("1");
				tSysLocalNetwork.setNetworkid(UUID.randomUUID().toString());
				tSysLocalNetwork.setOperatorname(tSysUserinfo.getUserName());
				tSysLocalNetwork.setTSysFunction(f);
				tSysLocalNetwork.setUpdatetime(new Timestamp(new Date().getTime()));
				dataBaseDao.save(tSysLocalNetwork);
			}
		}
		
		//用户关联应用,供应商
		TSysUserselectedfunction tSysUserselectedfunction = new TSysUserselectedfunction();
		tSysUserselectedfunction.setFunctionId(f.getFunctionId());
		tSysUserselectedfunction.setIsAvailable("1");
		tSysUserselectedfunction.setShowHome("0");
		tSysUserselectedfunction.setOperatorAccount(tSysUserinfo.getUserId());
		tSysUserselectedfunction.setOperatorName(tSysUserinfo.getUserName());
		tSysUserselectedfunction.setUserFunctionId(UUID.randomUUID().toString());
		tSysUserselectedfunction.setUserId(tSysUserinfo.getUserId());
		tSysUserselectedfunction.flushUpdateTime();
		tSysUserselectedfunction.setUpdateTime(new Timestamp(new Date().getTime()));
		dataBaseDao.save(tSysUserselectedfunction);
		
		//应用授权接口
		if(authRows != null){
			for(int i=0;i<authRows.length;i++){
				TSysInterfaceApp tSysInterfaceApp = new TSysInterfaceApp();
				tSysInterfaceApp.setInterfaceappid(UUID.randomUUID().toString());
				tSysInterfaceApp.setIsavailable("1");
				tSysInterfaceApp.setOperatorname(tSysUserinfo.getUserName());
				tSysInterfaceApp.setTSysFunction(f);
				TSysInterfaceInfo tSysInterfaceInfo = new TSysInterfaceInfo();
				tSysInterfaceInfo.setInterfaceid(authRows[i]);
				tSysInterfaceApp.setTSysInterfaceInfo(tSysInterfaceInfo);
				tSysInterfaceApp.setUpdatetime(new Timestamp(new Date().getTime()));
				dataBaseDao.save(tSysInterfaceApp);
			}
		}
		
		//应用截图
		if(imgShots!=null){
			for(int i=0;i<imgShots.length;i++){
				String pathHead = this.getClass().getClassLoader().getResource("/").getPath().replace("/WEB-INF/classes", "");
				String pathBody = "/upload/appIconImg/"+UUID.randomUUID().toString()+".jpg";
				Base64Image.GenerateImage(imgShots[i], pathHead + pathBody);
				TMarketScreenshots tMarketScreenshots = new TMarketScreenshots();
				tMarketScreenshots.setCreateTime(new Timestamp(new Date().getTime()));
				tMarketScreenshots.setIsAvailable("1");
				tMarketScreenshots.setOperatorName(tSysUserinfo.getUserName());
				tMarketScreenshots.setPicUrl(pathBody);
				tMarketScreenshots.setShotId(UUID.randomUUID().toString());
				tMarketScreenshots.setTSysFunction(f);
				tMarketScreenshots.setUpdateTime(new Timestamp(new Date().getTime()));
				dataBaseDao.save(tMarketScreenshots);
			}
		}
		return RtnCodeConstant.RTN_CODE_SUCCESS;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<Map> getInfo(String functionId) throws ErrorSqlException {
		TSysFunction tSysFunction = (TSysFunction) dataBaseDao.load(TSysFunction.class, functionId);
		List params = new ArrayList();
		params.add(functionId);
		List listTSysLocalNetwork = dataBaseDao.queryForList("t_sys_local_network.list", params);
		List listTSysInterfaceApp = dataBaseDao.queryForList("t_sys_interface_info.listByFunctionId", params);
		List listTMarketScreenshots = dataBaseDao.queryForList("t_market_screenshots.list", params);
		List result = new ArrayList();
		Map m = BeanUtil.beanToMap(tSysFunction);
		m.put("listTSysLocalNetwork", listTSysLocalNetwork);
		m.put("listTSysInterfaceApp", listTSysInterfaceApp);
		m.put("listTMarketScreenshots", listTMarketScreenshots);
		result.add(m);
		return result;
	}

	public String updateApp(String[] imgShots, String appIcon,
			String functionName, String functionNameEn, String deploymentType,
			String actionUrl, String appZipUrl, String appSize,
			String versionName, String[] ipAddress, String[] ipAddressDesc,
			String net_setting, String manageUrl,
			String description, String upgradeContent, String[] authRows,
			String functionId) throws ErrorSqlException {
		//redis里取登录人
		TSysUserinfo tSysUserinfo = loginUser();
		
		TSysFunction f = (TSysFunction) dataBaseDao.load(TSysFunction.class, functionId);
		f.setActionUrl(actionUrl);

		//byte计算为M
		File appZipFile=new File(this.getClass().getResource("/").getPath().replace("WEB-INF/classes/", "")+appZipUrl);
		f.setAppSize(StringUtil.convertFileSize(appZipFile.length()));
		
		f.setAppZipUrl(appZipUrl);
		f.setDeploymentType(deploymentType);
		f.setDescription(description);
		f.setFunctionName(functionName);
		f.setFunctionNameEn(functionNameEn);
		f.setInternetConfig(net_setting);
		
		//应用图标
		if(StringUtils.isNotEmpty(appIcon)){
			String appIconPathHead = this.getClass().getClassLoader().getResource("/").getPath().replace("/WEB-INF/classes", "");
			String appIconPathBody = "/upload/appIconImg/"+UUID.randomUUID().toString()+".jpg";
			Base64Image.GenerateImage(appIcon, appIconPathHead + appIconPathBody);
			f.setIconName(appIconPathBody);
		}
		f.setManageUrl(manageUrl);
		f.setOperatorAccount(tSysUserinfo.getUserId());
		f.setOperatorName(tSysUserinfo.getUserName());
		f.setProvider(tSysUserinfo.getUserName());
		f.setUpdateTime(new Timestamp(new Date().getTime()));
		f.setUpgradeContent(upgradeContent);
		f.setVersionName(versionName);
		dataBaseDao.update(f);
		
		//局域网信息
			//清空
		List list = dataBaseDao.getHibernateTemplate().find(" from TSysLocalNetwork t where t.TSysFunction.functionId=? ", functionId);
		dataBaseDao.getHibernateTemplate().deleteAll(list);
		if(ipAddress!=null && StringUtils.equals(f.getInternetConfig(), "1")){
			for(int i=0;i<ipAddress.length;i++){
				TSysLocalNetwork tSysLocalNetwork = new TSysLocalNetwork();
				tSysLocalNetwork.setAddress(ipAddressDesc[i]);
				tSysLocalNetwork.setIp(ipAddress[i]);
				tSysLocalNetwork.setIsavailable("1");
				tSysLocalNetwork.setNetworkid(UUID.randomUUID().toString());
				tSysLocalNetwork.setOperatorname(tSysUserinfo.getUserName());
				tSysLocalNetwork.setTSysFunction(f);
				tSysLocalNetwork.setUpdatetime(new Timestamp(new Date().getTime()));
				dataBaseDao.save(tSysLocalNetwork);
			}
		}
		
		//应用授权接口
			//清空
		list = dataBaseDao.getHibernateTemplate().find(" from TSysInterfaceApp t where t.TSysFunction.functionId=? ", functionId);
		dataBaseDao.getHibernateTemplate().deleteAll(list);
		if(authRows != null){
			for(int i=0;i<authRows.length;i++){
				TSysInterfaceApp tSysInterfaceApp = new TSysInterfaceApp();
				tSysInterfaceApp.setInterfaceappid(UUID.randomUUID().toString());
				tSysInterfaceApp.setIsavailable("1");
				tSysInterfaceApp.setOperatorname(tSysUserinfo.getUserName());
				tSysInterfaceApp.setTSysFunction(f);
				TSysInterfaceInfo tSysInterfaceInfo = new TSysInterfaceInfo();
				tSysInterfaceInfo.setInterfaceid(authRows[i]);
				tSysInterfaceApp.setTSysInterfaceInfo(tSysInterfaceInfo);
				tSysInterfaceApp.setUpdatetime(new Timestamp(new Date().getTime()));
				dataBaseDao.save(tSysInterfaceApp);
			}
		}
		
		//应用截图
			//清空
		if(imgShots == null){
			list = dataBaseDao.getHibernateTemplate().find(" from TSysInterfaceApp t where t.TSysFunction.functionId=? and  ", functionId);
			dataBaseDao.getHibernateTemplate().deleteAll(list);
		}else{
			String imgShotParams = "";
			for(int i=0;i<imgShots.length;i++){
				if(StringUtils.contains(imgShots[i], "upload"))
					imgShotParams += "," + imgShots[i].substring(imgShots[i].indexOf("/upload"));
			}
			if(StringUtils.isNotEmpty(imgShotParams))
				imgShotParams = imgShotParams.substring(1);
			list = dataBaseDao.getHibernateTemplate().find(" from TMarketScreenshots t where t.TSysFunction.functionId=? and t.picUrl not in ("+StringUtil.concatStrForSql(imgShotParams)+") ", functionId);
			dataBaseDao.getHibernateTemplate().deleteAll(list);
		}
		if(imgShots!=null){
			for(int i=0;i<imgShots.length;i++){
				if(StringUtils.contains(imgShots[i], "upload"))
					continue;
				String pathHead = this.getClass().getClassLoader().getResource("/").getPath().replace("/WEB-INF/classes", "");
				String pathBody = "/upload/appIconImg/"+UUID.randomUUID().toString()+".jpg";
				Base64Image.GenerateImage(imgShots[i], pathHead + pathBody);
				TMarketScreenshots tMarketScreenshots = new TMarketScreenshots();
				tMarketScreenshots.setCreateTime(new Timestamp(new Date().getTime()));
				tMarketScreenshots.setIsAvailable("1");
				tMarketScreenshots.setOperatorName(tSysUserinfo.getUserName());
				tMarketScreenshots.setPicUrl(pathBody);
				tMarketScreenshots.setShotId(UUID.randomUUID().toString());
				tMarketScreenshots.setTSysFunction(f);
				tMarketScreenshots.setUpdateTime(new Timestamp(new Date().getTime()));
				dataBaseDao.save(tMarketScreenshots);
			}
		}
		return RtnCodeConstant.RTN_CODE_SUCCESS;
	}
	
	public void copyFunctionToVersion(TSysFunction function) throws ErrorSqlException, IOException{
		
		//修改旧版本数据状态
		String sql="update T_SYS_FUNCTION_VERSION set ISAVAILABLE=0 where FUNCTIONID=?";
		this.dataBaseDao.getJdbcTemplate().update(sql,function.getFunctionId());
		
		TSysFunctionVersion version=new TSysFunctionVersion();
		version.setVersionid(UUID.randomUUID().toString());
		version.setFunctionid(function.getFunctionId());
		version.setFunctionname(function.getFunctionName());
		version.setDescription(function.getDescription());
		version.setIconname(function.getIconName());
		version.setActionurl(function.getActionUrl());
		version.setPriority(function.getPriority().doubleValue());
		version.setAppsize(function.getAppSize());
		version.setAppzipurl(function.getAppZipUrl());
		version.setAppdownctn(function.getAppDownCtn().doubleValue());
		
		version.setProvider(function.getProvider());
		version.setSubmittime(function.getSubmitTime());
		version.setAuditor(function.getAuditor());
		version.setAuditingtime(function.getAuditingTime());
		version.setState(function.getState());
		
		version.setVersionname(function.getVersionName());
		version.setVersionno(function.getVersionNo());
		version.setDeploymenttype(function.getDeploymentType());
		
		version.setAcceptanceresult(function.getAcceptanceResult());
		version.setManageurl(function.getManageUrl());
		version.setUpdatetime(new Timestamp(System.currentTimeMillis()));
		version.setOperatoraccount(loginUser().getUserId());
		version.setOperatorname(loginUser().getUserName());
		version.setIsavailable(DBConstant.DB_STATUS_ABLCE);
		
		version.setUpgradecontent(function.getUpgradeContent());
		
		dataBaseDao.save(version);
		
		//把备份文件copy到versionId.zip,如果没有_,则跳
		String oldZipPath = this.getClass().getClassLoader().getResource("/").getPath().replace("/WEB-INF/classes", "") + "upload/zip/" + function.getFunctionId() + "_.zip";
		if(new File(oldZipPath).exists()){
			String newZipPath = this.getClass().getClassLoader().getResource("/").getPath().replace("/WEB-INF/classes", "")  + "upload/zip/" + version.getVersionid() + ".zip";
			FileUtils.copyFile(new File(oldZipPath), new File(newZipPath));
			FileUtils.deleteQuietly(new File(oldZipPath));
		}
	}
	
	
	public String updateUpgradeApp(String[] imgShots, String appIcon,
			String functionName, String functionNameEn, String deploymentType,
			String actionUrl, String appZipUrl, String appSize,
			String versionName, String[] ipAddress, String[] ipAddressDesc,
			String net_setting, String manageUrl,
			String description, String upgradeContent, String[] authRows,
			String functionId) throws ErrorSqlException, IOException {
		//redis里取登录人
		TSysUserinfo tSysUserinfo = loginUser();
		
		//只修改应用表对应应用状态
		TSysFunction f = (TSysFunction) dataBaseDao.load(TSysFunction.class, functionId);
		//复制到version表  复制zip成versionId
		copyFunctionToVersion(f);
		f.setState(Constants.UPDATE_PENDING);
		dataBaseDao.update(f);
		 
		//将升级插入到
		TSysFunctionUpdatePending tp=new TSysFunctionUpdatePending();
		tp.setPendid(UUID.randomUUID().toString());
		
		tp.setTSysFunction(f);
		tp.setActionurl(actionUrl);
		tp.setAppzipurl(appZipUrl);
		
		//byte计算为M
		File appZipFile=new File(this.getClass().getResource("/").getPath().replace("WEB-INF/classes/", "")+appZipUrl);
		f.setAppSize(StringUtil.convertFileSize(appZipFile.length()));
		tp.setAppsize(f.getAppSize());
		
		tp.setDeploymenttype(deploymentType);
		tp.setDescription(description);
		tp.setFunctionname(functionName);
		tp.setFunctionnameen(functionNameEn);
		tp.setInternetconfig("");
		
		//应用图标
		if(StringUtils.isNotEmpty(appIcon)){
			String appIconPathHead = this.getClass().getClassLoader().getResource("/").getPath().replace("/WEB-INF/classes", "");
			String appIconPathBody = "/upload/appIconImg/"+UUID.randomUUID().toString()+".jpg";
			Base64Image.GenerateImage(appIcon, appIconPathHead + appIconPathBody);
			tp.setIconname(appIconPathBody);
		}
		else{
			tp.setIconname(f.getIconName());
		}
		tp.setManageurl(manageUrl);
		tp.setOperatoraccount(tSysUserinfo.getUserId());
		tp.setOperatorname(tSysUserinfo.getUserName());
		tp.setProvider(tSysUserinfo.getUserName());
		tp.setUpdatetime(new Timestamp(System.currentTimeMillis()));
		tp.setUpgradecontent(upgradeContent);
		tp.setVersionname(versionName);
		tp.setVersionno(f.getVersionNo()+1);
		tp.setAcceptanceresult(null);
		tp.setIsavailable("1");
		dataBaseDao.save(tp);
		
		//局域网信息
		//清空
		List list = dataBaseDao.getHibernateTemplate().find(" from TSysLocalNetwork t where t.TSysFunction.functionId=? ", functionId);
		dataBaseDao.getHibernateTemplate().deleteAll(list);
		if(ipAddress!=null){
			for(int i=0;i<ipAddress.length;i++){
				TSysLocalNetwork tSysLocalNetwork = new TSysLocalNetwork();
				tSysLocalNetwork.setAddress(ipAddressDesc[i]);
				tSysLocalNetwork.setIp(ipAddress[i]);
				tSysLocalNetwork.setIsavailable("1");
				tSysLocalNetwork.setNetworkid(UUID.randomUUID().toString());
				tSysLocalNetwork.setOperatorname(tSysUserinfo.getUserName());
				tSysLocalNetwork.setTSysFunction(f);
				tSysLocalNetwork.setUpdatetime(new Timestamp(new Date().getTime()));
				dataBaseDao.save(tSysLocalNetwork);
			}
		}
		
		//应用授权接口
		//清空
		list = dataBaseDao.getHibernateTemplate().find(" from TSysInterfaceApp t where t.TSysFunction.functionId=? ", functionId);
		dataBaseDao.getHibernateTemplate().deleteAll(list);
		if(authRows != null){
			for(int i=0;i<authRows.length;i++){
				TSysInterfaceApp tSysInterfaceApp = new TSysInterfaceApp();
				tSysInterfaceApp.setInterfaceappid(UUID.randomUUID().toString());
				tSysInterfaceApp.setIsavailable("1");
				tSysInterfaceApp.setOperatorname(tSysUserinfo.getUserName());
				tSysInterfaceApp.setTSysFunction(f);
				TSysInterfaceInfo tSysInterfaceInfo = new TSysInterfaceInfo();
				tSysInterfaceInfo.setInterfaceid(authRows[i]);
				tSysInterfaceApp.setTSysInterfaceInfo(tSysInterfaceInfo);
				tSysInterfaceApp.setUpdatetime(new Timestamp(new Date().getTime()));
				dataBaseDao.save(tSysInterfaceApp);
			}
		}
		
		//应用截图
		//清空
		if(imgShots == null){
			list = dataBaseDao.getHibernateTemplate().find(" from TSysInterfaceApp t where t.TSysFunction.functionId=? and  ", functionId);
			dataBaseDao.getHibernateTemplate().deleteAll(list);
		}else{
			String imgShotParams = "";
			for(int i=0;i<imgShots.length;i++){
				if(StringUtils.contains(imgShots[i], "upload"))
					imgShotParams += "," + imgShots[i].substring(imgShots[i].indexOf("/upload"));
			}
			if(StringUtils.isNotEmpty(imgShotParams))
				imgShotParams = imgShotParams.substring(1);
			list = dataBaseDao.getHibernateTemplate().find(" from TMarketScreenshots t where t.TSysFunction.functionId=? and t.picUrl not in ("+StringUtil.concatStrForSql(imgShotParams)+") ", functionId);
			dataBaseDao.getHibernateTemplate().deleteAll(list);
		}
		if(imgShots!=null){
			for(int i=0;i<imgShots.length;i++){
				if(StringUtils.contains(imgShots[i], "upload"))
					continue;
				String pathHead = this.getClass().getClassLoader().getResource("/").getPath().replace("/WEB-INF/classes", "");
				String pathBody = "/upload/appIconImg/"+UUID.randomUUID().toString()+".jpg";
				Base64Image.GenerateImage(imgShots[i], pathHead + pathBody);
				TMarketScreenshots tMarketScreenshots = new TMarketScreenshots();
				tMarketScreenshots.setCreateTime(new Timestamp(new Date().getTime()));
				tMarketScreenshots.setIsAvailable("1");
				tMarketScreenshots.setOperatorName(tSysUserinfo.getUserName());
				tMarketScreenshots.setPicUrl(pathBody);
				tMarketScreenshots.setShotId(UUID.randomUUID().toString());
				tMarketScreenshots.setTSysFunction(f);
				tMarketScreenshots.setUpdateTime(new Timestamp(new Date().getTime()));
				dataBaseDao.save(tMarketScreenshots);
			}
		}
		return RtnCodeConstant.RTN_CODE_SUCCESS;
	}
}
